<template>
  <el-container>
    <el-main>
      <div class="upload-main">
        <el-form
          ref="filesForm"
          :model="filesForm"
          :rules="rules"
          label-width="120px"
          class="form"
        >
          <el-col :span="24">
            <el-form-item label="防雷单位" prop="lp_unit_id">
              <el-select
                v-model="filesForm.lp_unit_id"
                filterable
                :disabled="filesForm.testing_report_id !== ''"
                placeholder="请选择防雷单位"
                class="testingInstitutionId"
                size="small"
              >
                <el-option
                  v-for="(item, index) in tableData"
                  :key="index"
                  :label="item.unit_name"
                  :value="item.lp_unit_id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="检测机构" prop="testing_institution_id">
              <el-select
                v-model="filesForm.testing_institution_id"
                filterable
                placeholder="请选择检测机构"
                class="testingInstitutionId"
                @change="handleChangeTest"
                size="small"
              >
                <el-option
                  v-for="(item, index) in company"
                  :key="index"
                  :label="item.codeName"
                  :value="item.codeValue"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="报告有效期" prop="date">
              <el-date-picker
                style="width: 100%"
                v-model="filesForm.date"
                type="daterange"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handleDate"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审查人">
              <el-input
                placeholder="请输入审查人"
                v-model="filesForm.check_person"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审查时间">
              <el-date-picker
                style="width: 100%"
                v-model="filesForm.check_time"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审查意见">
              <el-input
                placeholder="请输入审查意见"
                type="textarea"
                v-model="filesForm.check_opinion"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="报告名称" prop="report_name">
              <el-input
                v-model="filesForm.report_name"
                placeholder="请输入报告名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="报告类别" prop="proofId">
              <el-select
                v-model="filesForm.proofId"
                filterable
                placeholder="请选择报告类别"
                class="testingInstitutionId"
                @change="handleChangeSort"
                size="small"
              >
                <el-option
                  v-for="(item, index) in items"
                  :key="index"
                  :label="item.check_required_content"
                  :value="item.field_name"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>

        <div class="upload-item">
          <el-upload
            :action="actions"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :headers="token"
            :limit="fileLimit"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :on-preview="handlePreview"
            accept=".pdf,.PDF"
            :on-success="handleSuccess"
          >
            <el-button size="small" v-if="readonly !== 1" type="primary"
              >上传报告</el-button
            >
          </el-upload>
        </div>
        <div class="text-center">
          <el-button @click="$router.push('/waterMark')">返回</el-button>
          <el-button
            type="primary"
            @click="handleSubmit('filesForm')"
            v-if="readonly !== 1"
            >提交</el-button
          >
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import addtable from "@/mixins/addtable";
import {
  getTestCompany,
  uploadAdd,
  queryItems,
  findByIdDetail,
  uploadEdit,
} from "./api";
import { getCompanyList } from "@/api";
import { getToken } from "@/utils/auth";

import uploadItem from "./upload-item";
export default {
  mixins: [addtable],
  components: {
    uploadItem,
  },
  data() {
    return {
      // tableName: "衢州市防雷安全检查表",
      token: {
        accessToken: getToken(),
      },
      searchForm: {
        q_unit_name: "",
        q_unit_type: "",
        q_lp_grade: "",
        q_testing_report_cycle: "",
      },
      tableData: [],
      items: [],
      actions: "",

      rules: {
        lp_unit_id: [
          { required: true, message: "请选择防雷单位", trigger: "change" },
        ],
        testing_institution_id: [
          { required: true, message: "请选择检测机构", trigger: "change" },
        ],
        proofId: [
          { required: true, message: "请选择上传类别", trigger: "change" },
        ],
        report_name: [
          { required: true, message: "请输入报告", trigger: "blur" },
        ],
        date: [
          {
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
      },

      fileLimit: 5,
      readonly: 0,
      fileList: [],

      company: [],

      filesForm: {
        cmdb_met_testing_report_item: [],
        lp_unit_id: "",
        testing_institution_id: "",
        report_name: "",
        start_validate: "",
        end_validate: "",
        testing_report_id: "",
        check_person: "",
        check_time: "",
        check_opinion: "",
        check_status: 0,
        proofId: "",
        date: "",
      },
    };
  },

  created() {
    this.filesForm.testing_report_id = this.$route.query.reportId || "";
    this.readonly = this.$route.query.readonly || 0;
    if (this.filesForm.testing_report_id) {
      this.getDetail();
    }
    this.getTableData();
  },
  methods: {
    getTableData() {
      this.loading = true;
      this.getTableParams();
      this.tableParams.limit = 2000;
      getCompanyList(this.tableParams)
        .then((res) => {
          if (!res) return;
          const { data } = res;
          this.tableData = data;
        })
        .catch((err) => {
          console.log("TCL: getTableData -> err", err);
        });

      getTestCompany()
        .then(({ data }) => {
          this.company = data;
        })
        .catch((err) => {});

      queryItems()
        .then((res) => {
          if (!res) return;
          const { data } = res;
          this.items = data;
        })
        .catch((err) => {});
    },

    handleChangeTest(id) {
      console.log(
        "🚀 ~ file: upload.vue ~ line 267 ~ handleChangeTest ~ id",
        id
      );
      this.actions =
        process.env.VUE_APP_BASE_API +
        `/v1/plugins/met/testingReport/upload?testingInstitutionId=${id}`;
    },

    handleChangeSort(proofId) {
      const arr = this.filesForm.cmdb_met_testing_report_item.filter(
        (item) =>
          item.check_item_field_name === proofId &&
          item.testing_report_id == this.filesForm.testing_report_id
      );
      this.fileList = arr.map((item) => {
        console.log(
          "🚀 ~ file: upload.vue ~ line 279 ~ this.fileList=arr.map ~ item",
          item
        );
        item.name = item.file_urls.split("/").pop();
        item.url = item.file_urls;
        item.ids = item.file_ids;
        return item;
      });
    },

    handleRemove(file, fileList) {
      this.fileList = fileList;
      console.log(
        "🚀 ~ file: upload.vue ~ line 299 ~ handleRemove ~  this.fileArray",
        this.fileList
      );
      console.log(file, fileList);
    },

    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择${this.fileLimit}个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    //点击文件列表中已上传文件进行下载
    handlePreview(file) {
      const link = file.url;
      const name = file.name;
      this.$message.info(`正在下载${name},请稍后！`);
      const a_link = document.createElement("a"); // 生成一个a链接
      fetch(link) // 括号里是文件链接
        .then((res) => res.blob())
        .then((blob) => {
          // 将链接地址字符内容转变成blob地址
          a_link.href = URL.createObjectURL(blob);
          console.log(a_link.href);
          a_link.download = name; //下载的文件的名字
          document.body.appendChild(a_link);
          a_link.click();
        });
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleSuccess(response, file, fileList) {
      const data = response.data;
      const obj = {
        name: data.fileName,
        url: data.fileUrl,
        ids: data.fileId,
      };
      this.fileList.push(obj);
    },

    handleSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(
            "🚀 ~ file: upload.vue ~ line 333 ~ this.$refs[formName].validate ~ this.filesArray",
            this.fileList
          );
          this.filesForm.cmdb_met_testing_report_item = this.fileList.map(
            (item) => {
              item.file_ids = item.ids;
              item.file_urls = item.url;
              item.check_item_field_name = this.filesForm.proofId;
              return item;
            }
          );
          this.filesForm.cmdb_met_testing_report_item = JSON.stringify(
            this.filesForm.cmdb_met_testing_report_item
          );
          !this.filesForm.testing_report_id
            ? uploadAdd(this.filesForm)
                .then(({ success, message }) => {
                  if (success) {
                    this.$message.success(message);
                    this.init();
                  } else {
                    this.$message.error(message);
                  }
                })
                .catch((err) => {})
            : uploadEdit(this.filesForm)
                .then(({ success, message }) => {
                  if (success) {
                    this.$message.success(message);
                    this.init();
                  } else {
                    this.$message.error(message);
                  }
                })
                .catch((err) => {});
        }
      });
    },

    getDetail() {
      findByIdDetail(this.filesForm.testing_report_id)
        .then(({ data }) => {
          console.log("🚀 ~ file: upload.vue ~ line 376 ~ .then ~ data", data);
          for (const key in data) {
            this.filesForm[key] = data[key];
          }
          this.filesForm.date = [
            this.filesForm.start_validate,
            this.filesForm.end_validate,
          ];
          this.filesForm.testing_institution_id =
            "" + data.testing_institution_id + "";
          this.filesForm.start_validate = data.start_validate.split(" ")[0];
          this.filesForm.end_validate = data.end_validate.split(" ")[0];
          // this.filesForm.created_time = null;
          // this.filesForm.check_time = null;
          // this.filesForm.updated_time = null;
          this.actions =
            process.env.VUE_APP_BASE_API +
            `/v1/plugins/met/testingReport/upload?testingInstitutionId=${data.testing_institution_id}`;
        })
        .catch((err) => {});
    },
    handleDate(date) {
      if (date) {
        this.filesForm.start_validate = date[0];
        this.filesForm.end_validate = date[1];
      }
    },

    init() {
      this.fileList = [];
      this.fileArray = [];
      this.filesForm.proofId = "";
      this.filesForm.report_name = "";
      this.filesForm.cmdb_met_testing_report_item = [];
    },
  },
};
</script>

<style lang="scss" scoped>
.upload-main {
  width: 1000px;
  background: #fff;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  padding: 20px;
}

.upload-item {
  height: 200px;
  box-sizing: border-box;
  padding: 0 120px;
}

.upload {
  display: flex;
  justify-content: center;
  > div {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}
</style>
